﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.Administration;
using System.Web.Services;
using System.Security;
using System.Linq;
using Microsoft.Office.SecureStoreService.Server;
using Microsoft.BusinessData.Infrastructure.SecureStore;

namespace TFSWITConnector
{
    public partial class RibbonCustomControlsASPX : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //base.OnLoad(e);
            if (!this.IsPostBack)
            {
                var spWeb = SPControl.GetContextSite(Context).RootWeb;
                SPPropertyBag spProperties = spWeb.Properties;

                //ShowMessage(Context.User.Identity.Name);

                string qstrId = Page.Request.QueryString["ActionId"];
                string errormessage = "";

                if (qstrId == "tfswitconngroup.ExportWITSchema")
                {
                    errormessage = ExportWITSchema(spProperties);
                    Response.Redirect("../Settings.aspx");
                }

                //SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, errormessage);
                //Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('" + errormessage + "');</script>"); //commitPopup
                //Response.End();
            }
        }

        [WebMethod]
        public static string ValidateTFSConnection()
        {
            string errormessage;
            var spWeb = SPControl.GetContextSite(HttpContext.Current).RootWeb;
            SPPropertyBag spProperties = spWeb.Properties;

            if (ValidateTFS(spProperties, out errormessage))
            {
                return "TFS connection is OK!";
            }
            else
                return errormessage;
        }

        string ExportWITSchema(SPPropertyBag spProperties)
        {
            string errormessage = "";

            if (ValidateTFS(spProperties, out errormessage))
            {
                string tfsProjName = GetProperty(spProperties, "LobSystem_TFSProjectName", out errormessage);
                string tfsConnUrl = GetProperty(spProperties, "LobSystem_TFSServerURL", out errormessage);
                var tfsUser = GetTfsCredentials(spProperties, out errormessage);

                if (tfsProjName != null)
                {
                    Response.Clear();
                    Response.ContentType = "application/x-msdownload";  //"text/xml";
                    Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(tfsProjName + ".zip"));
                    Response.BinaryWrite(TFSSPConnector.CustomLobSystem.ExportAllTFSWorkItemDefinitions(tfsConnUrl, tfsUser, tfsProjName));
                    Response.End();
                }
            }

            return errormessage;
        }

        [WebMethod]
        public static string CreateCustomLobSystem()
        {
            string errormessage;
            var spSite = SPControl.GetContextSite(HttpContext.Current);
            SPPropertyBag spProperties = spSite.RootWeb.Properties;

            if (ValidateTFS(spProperties, out errormessage))
            {
                var lobsystemdata = new TFSSPConnector.CustomLobSystemStructure
                {
                    Attachment_EntityName = GetProperty(spProperties, "Attachment_EntityName", out errormessage),
                    Attachment_ShowInItemView = GetProperty(spProperties, "Attachment_ShowInItemView", out errormessage),
                    Attachment_ShowInListView = GetProperty(spProperties, "Attachment_ShowInListView", out errormessage),
                    LobSystem_Name = GetProperty(spProperties, "LobSystem_Name", out errormessage),
                    LobSystem_SPSiteURL = spSite.Url,
                    LobSystem_TFSProjectName = GetProperty(spProperties, "LobSystem_TFSProjectName", out errormessage),
                    LobSystem_TFSServerURL = GetProperty(spProperties, "LobSystem_TFSServerURL", out errormessage),
                    LobSystem_AppID = GetTfsCredentials(spProperties, out errormessage),
                    WorkItem_ReadOnlyFields = GetProperty(spProperties, "WorkItem_ReadOnlyFields", out errormessage),
                    WorkItem_RequiredInForms = GetProperty(spProperties, "WorkItem_RequiredInForms", out errormessage),
                    WorkItem_ShowInItemView = GetProperty(spProperties, "WorkItem_ShowInItemView", out errormessage),
                    WorkItem_ShowInListView = GetProperty(spProperties, "WorkItem_ShowInListView", out errormessage)
                };

                if (!lobsystemdata.ValidateFields())
                {
                    return "Some of LobSystem properties are undefined";
                }

                SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                //BdcService bdcSvc = SPFarm.Local.Services.GetValue<BdcService>(String.Empty); //spSite.WebApplication.Farm
                SPServiceContext srvcontext = SPServiceContext.Current;
                //var catalog = bdcSvc.GetAdministrationMetadataCatalog(srvcontext);

                var proxy = (BdcServiceApplicationProxy)srvcontext.GetDefaultProxy(typeof(BdcServiceApplicationProxy));
                var catalog = proxy.GetAdministrationMetadataCatalog();

                //var acl = catalog.GetAccessControlList();
                //acl.Add(new IndividualAccessControlEntry(BdcAccessControlList.TranslateFriendlyStringToEncodedClaim("Domain\\Admin"), BdcRights.Execute | BdcRights.Edit | BdcRights.SelectableInClients | BdcRights.SetPermissions));
                //catalog.SetAccessControlList(acl); //Set the permissions 
                //catalog.CopyAclAcrossChildren(); 

                if (TFSSPConnector.CustomLobSystem.CreateCustomLobSystem(lobsystemdata, catalog, proxy, diagSvc, out errormessage))
                    return "Creation of LobSystem structure is finished";
                else
                    return errormessage;
            }
            else
                return errormessage;
        }

        static string GetProperty(SPPropertyBag spProperties, string name, out string errormessage)
        {
            if (!spProperties.ContainsKey(name))
            {
                errormessage = name + " is undefined";
                return null;
            }

            string value = spProperties[name];
            if (value == null)
            {
                errormessage = name + " is null";
                return "";
            }

            errormessage = "";
            return value;
        }

        static bool ValidateTFS(SPPropertyBag spProperties, out string errormessage)
        {
            if (!spProperties.ContainsKey("LobSystem_TFSServerURL"))
            {
                errormessage = "TFS Connection URL is undefined";
                return false;
            }

            var LobSystem_AppID = GetTfsCredentials(spProperties, out errormessage);
            if (errormessage != null)
            {
                return false;
            }

            string LobSystem_TFSServerURL = spProperties["LobSystem_TFSServerURL"];
            if (string.IsNullOrEmpty(LobSystem_TFSServerURL))
            {
                errormessage = "TFS Connection URL is undefined";
                return false;
            }

            bool res = TFSSPConnector.CustomLobSystem.ValidateTFSConnection(LobSystem_TFSServerURL, LobSystem_AppID, out errormessage);
            if (!res)
            {
                if (errormessage == null) errormessage = "Cannot connect to TFS";
                return false;
            }

            errormessage = null;
            return true;
        }

        internal static SecureStoreCredentialCollection GetTfsCredentials(SPPropertyBag spProperties, out string errormessage)
        {
            string LobSystem_TFSCredentials = GetProperty(spProperties, "LobSystem_TFSCredentials", out errormessage);
            string LobSystem_AppID = GetProperty(spProperties, "LobSystem_AppID", out errormessage);
            if (LobSystem_TFSCredentials == "SSS" && string.IsNullOrEmpty(LobSystem_AppID))
            {
                errormessage = "Secure Store Application ID is empty";
                return null;
            }
            if (LobSystem_TFSCredentials == "SPU")
            {
                LobSystem_AppID = null;
                errormessage = null;
            }

            if (LobSystem_TFSCredentials == "SSS" && !string.IsNullOrEmpty(LobSystem_AppID))
            {
                return CustomLobSystemData.GetSSSCredentials(LobSystem_AppID, out errormessage);
            }

            return null;
        }
    }
}
